package com.lengxf.netty.config.listener;

import com.lengxf.netty.config.ChannelContextHolder;
import com.lengxf.netty.config.NettyClientConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author Lengxf
 * @version 1.0.0
 * @ClassName ConnectionListener.java
 * @Description
 * @createTime 2022-10-10日 17:42:00
 */
@Slf4j
@ChannelHandler.Sharable
public class ConnectionListener implements ChannelFutureListener {

    @Override
    public void operationComplete(ChannelFuture channelFuture) {
        if (!needReconnect(channelFuture)) {
            return;
        }
        final EventLoop loop = channelFuture.channel().eventLoop();
        log.error("netty server is error,now reConnect,delayTime is {} s...", NettyClientConfig.getDelayTime());
        loop.schedule(() -> ChannelContextHolder.getNettyClient()
                .createBootstrap(new Bootstrap(), loop), NettyClientConfig.getDelayTime(), TimeUnit.SECONDS);
    }

    private Boolean needReconnect(ChannelFuture channelFuture) {
        if (channelFuture.isSuccess()) {
            boolean b = ChannelContextHolder.getShouldReconnect().get();
            if (!b) {
                //不需要重连时增加通道关闭监听
                channelFuture.channel().closeFuture().addListener(this);
            }
            return b;
        }
        return ChannelContextHolder.setShouldReconnect(true);
    }

}
